package org.jeecg.modules.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wms.entity.WmsWarehouse;
import org.jeecg.modules.wms.service.IWmsWarehouseService;
import org.jeecg.modules.wms.vo.WmsWarehouseLocationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 仓库信息控制器
 */
@Slf4j
@Api(tags = "仓库信息")
@RestController
@RequestMapping("/wms/warehouse")
public class WmsWarehouseController extends JeecgController<WmsWarehouse, IWmsWarehouseService> {

    @Autowired
    private IWmsWarehouseService wmsWarehouseService;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "仓库信息-分页列表查询")
    @ApiOperation(value = "仓库信息-分页列表查询", notes = "仓库信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(name = "warehouseCode", required = false) String warehouseCode,
                                   @RequestParam(name = "warehouseName", required = false) String warehouseName,
                                   @RequestParam(name = "warehouseType", required = false) String warehouseType,
                                   HttpServletRequest req) {
        
        // 手动构建查询条件
        QueryWrapper<WmsWarehouse> queryWrapper = new QueryWrapper<>();
        WmsWarehouse wmsWarehouse = new WmsWarehouse();

        // 添加查询条件
        if (StringUtils.isNotBlank(warehouseCode)) {
            wmsWarehouse.setWarehouseCode(warehouseCode);
        }
        if (StringUtils.isNotBlank(warehouseName)) {
            wmsWarehouse.setWarehouseName(warehouseName);
        }
        if (StringUtils.isNotBlank(warehouseType)) {
            wmsWarehouse.setWarehouseType(warehouseType);
        }
        
        // 默认按创建时间倒序
        queryWrapper.orderByDesc("create_time");
        
        Page<WmsWarehouse> page = new Page<>(pageNo, pageSize);
        IPage<WmsWarehouseLocationVO> pageList = wmsWarehouseService.queryWarehousePageList(page, wmsWarehouse);
        return Result.OK(pageList);
    }

    /**
     * 添加
     */
    @AutoLog(value = "仓库信息-添加")
    @ApiOperation(value = "仓库信息-添加", notes = "仓库信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody WmsWarehouse wmsWarehouse) {
        wmsWarehouseService.saveWarehouse(wmsWarehouse);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     */
    @AutoLog(value = "仓库信息-编辑")
    @ApiOperation(value = "仓库信息-编辑", notes = "仓库信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody WmsWarehouse wmsWarehouse) {
        wmsWarehouseService.updateWarehouse(wmsWarehouse);
        return Result.OK("编辑成功！");
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "仓库信息-通过id删除")
    @ApiOperation(value = "仓库信息-通过id删除", notes = "仓库信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        wmsWarehouseService.deleteWarehouse(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "仓库信息-批量删除")
    @ApiOperation(value = "仓库信息-批量删除", notes = "仓库信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        wmsWarehouseService.batchDeleteWarehouse(ids);
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "仓库信息-通过id查询")
    @ApiOperation(value = "仓库信息-通过id查询", notes = "仓库信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        WmsWarehouseLocationVO wmsWarehouseLocationVO = wmsWarehouseService.queryWarehouseById(id);
        return Result.OK(wmsWarehouseLocationVO);
    }
    
    /**
     * 切换仓库状态
     */
    @AutoLog(value = "仓库信息-切换状态")
    @ApiOperation(value = "仓库信息-切换状态", notes = "仓库信息-切换状态")
    @PutMapping(value = "/toggleStatus")
    public Result<?> toggleStatus(@RequestParam(name = "id", required = true) String id) {
        wmsWarehouseService.toggleWarehouseStatus(id);
        return Result.OK("操作成功！");
    }
    
    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmsWarehouse wmsWarehouse) {
        return super.exportXls(request, wmsWarehouse, WmsWarehouse.class, "仓库信息");
    }
    
    /**
     * 获取所有仓库列表（不分页）
     * 用于下拉选择框
     */
    @AutoLog(value = "仓库信息-获取所有仓库列表")
    @ApiOperation(value = "仓库信息-获取所有仓库列表", notes = "用于下拉选择框，返回所有可用仓库")
    @GetMapping(value = "/listAll")
    public Result<?> listAll(@RequestParam(name = "warehouseType", required = false) String warehouseType) {
        QueryWrapper<WmsWarehouse> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("warehouse_code");
        queryWrapper.eq("status", "0"); // 只获取启用状态的仓库
        
        // 如果传入了type参数，则按仓库类型过滤
        if (oConvertUtils.isNotEmpty(warehouseType)) {
            queryWrapper.eq("warehouse_type", warehouseType);
        }
        
        List<WmsWarehouse> list = wmsWarehouseService.list(queryWrapper);
        return Result.OK(list);
    }
    
    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WmsWarehouse.class);
    }

    /**
     * 根据ID批量获取仓库信息
     *
     * @param ids 仓库ID列表，多个ID使用逗号分隔
     * @return 仓库信息列表
     */
    @AutoLog(value = "仓库信息-根据ID批量获取")
    @ApiOperation(value = "根据ID批量获取仓库信息", notes = "根据ID批量获取仓库信息")
    @GetMapping(value = "/getWarehousesByIds")
    public Result<?> getWarehousesByIds(@RequestParam(name = "ids") String ids) {
        if (StringUtils.isEmpty(ids)) {
            return Result.error("参数不能为空");
        }
        String[] idArray = ids.split(",");
        List<String> idList = Arrays.asList(idArray);
        List<WmsWarehouse> warehouseList = wmsWarehouseService.listByIds(idList);
        return Result.OK(warehouseList);
    }

    /**
     * 根据物料类型获取推荐仓库
     *
     * @param materialTypes 物料类型，多个类型用逗号分隔
     * @return 推荐的仓库信息
     */
    @AutoLog(value = "仓库信息-根据物料类型获取推荐仓库")
    @ApiOperation(value = "根据物料类型获取推荐仓库", notes = "根据物料类型获取推荐仓库")
    @GetMapping(value = "/getRecommendedWarehouse")
    public Result<?> getRecommendedWarehouse(@RequestParam(name = "materialTypes") String materialTypes) {
        if (StringUtils.isEmpty(materialTypes)) {
            return Result.error("物料类型参数不能为空");
        }
        
        log.info("根据物料类型获取推荐仓库，materialTypes: {}", materialTypes);
        
        try {
            // 调用服务获取推荐仓库
            WmsWarehouse recommendedWarehouse = wmsWarehouseService.getRecommendedWarehouse(materialTypes);
            
            if (recommendedWarehouse == null) {
                return Result.error("未找到推荐仓库");
            }
            
            return Result.OK(recommendedWarehouse);
        } catch (Exception e) {
            log.error("获取推荐仓库失败", e);
            return Result.error("获取推荐仓库失败: " + e.getMessage());
        }
    }
} 